package com.py.credit.service.impl;

import com.py.credit.dao.DataEntryDao;
import com.py.credit.dao.DataLineageDao;
import com.py.credit.dao.DynamicSqlDao;
import com.py.credit.dao.TableDao;
import com.py.credit.entity.Column;
import com.py.credit.entity.DynamicSqlEntity;
import com.py.credit.entity.Table;
import com.py.credit.service.ColumnService;
import com.py.credit.service.DataLineageService;
import com.py.credit.service.excel.read.service.InspectDataStyleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据血缘分析服务实现
 *
 * @author YaoS
 * @version project2.6
 * @date 2019-01-24 11:32
 */
@Service
public class DataLineageServiceImpl implements DataLineageService {

    @Autowired
    TableDao tableDao;
    @Autowired
    DataEntryDao dataEntryDao;
    @Autowired
    DynamicSqlDao dynamicSqlDao;
    @Autowired
    DataLineageDao dataLineageDao;
    @Autowired
    ColumnService columnService;
    @Autowired
    @Qualifier("default")
    InspectDataStyleService inspectDataStyleService;

    /**
     * 功能描述: 查询旧数据值
     *
     * @param tableName 表名 不传时可设为空
     * @param recordId  资源ID,必传 可通过
     * @return HashMap 表中所有数据
     * @author YaoS
     * @date 19/1/24 10:55
     */
    private HashMap<String, Object> selectOldData(String tableName, String recordId) {
        tableName = "t_" + tableName;
        return dynamicSqlDao.selectTableInfoById(tableName, recordId, "");
    }

    @Override
    public boolean updateData(Integer tableId, String recordId, Map<String, Object> params) {
        StringBuilder error = new StringBuilder();
        StringBuilder keySb = new StringBuilder();
        String key = "";
        String value = "";
        //获取表信息
        Table table = tableDao.selectByPrimaryKey(tableId);
        //查询该表的业务字段
        List<Column> columns = columnService.getListByTableId(tableId);
        //查询旧值
        HashMap<String, Object> oldData = selectOldData(table.getResourceId(), recordId);
        List<Map<String, Object>> checkList = new ArrayList<>(1);
        Map<String, Object> checkMap = new HashMap<>(10);
        List<String> valueList = new ArrayList<>(10);

        //取出所有的业务字段key拼入keySb，取出value拼入valueList
        for (Column column : columns) {
            key = column.getMetricCode();
            //判断新的数据有没有key，有的话填入params中的值，否则填入oldData中的值
            value = String.valueOf(params.containsKey(key) ? params.get(key) : oldData.get(key));
            //如果是值为空或值为‘null’
            if ("".equals(value) || "null".equals(value)) {
                value = null;
            }
            keySb.append(key).append(",");
            valueList.add(value);
            checkMap.put(key, value);
        }
        checkList.add(checkMap);
        //进行数据重复性校验
        Map<String, Object> check = inspectDataStyleService.duplicationCheck(checkList, table, columns, false, true);
        String checkMessage = String.valueOf(check.get("duplicationMess"));
        if (null != check && StringUtils.isNotEmpty(checkMessage)) {
            error.append(checkMessage);
            return false;
        }
        String md5 = String.valueOf(checkList.get(0).get("MD5"));
        keySb.append("MD5").append(",");
        valueList.add(md5);
        //填入batchId
        String batchId = String.valueOf(oldData.get("batch_Id"));
        keySb.append("batch_Id").append(",");
        valueList.add(batchId);
        //填入tybm
        String tybm = String.valueOf(oldData.get("tybm"));
        keySb.append("tybm").append(",");
        valueList.add(tybm);
        //填入status
        String status = String.valueOf(oldData.get("status"));
        keySb.append("status");
        valueList.add(status);
        String sql = spliceSql("t_" + table.getResourceId(), keySb.toString(), valueList);
        System.out.println(sql);
        int oldId = (Integer) oldData.get("record_id");
        DynamicSqlEntity entity = new DynamicSqlEntity(sql);
        dynamicSqlDao.deleteTableInfo("t_" + table.getResourceId(), oldId + "");
        dataEntryDao.addData(entity);
        int newId = entity.getId();
        dataLineageDao.insertDataLineage(oldId, newId, tableId);
        return true;
    }

    /**
     * 功能描述: 拼接动态sql
     *
     * @param tableName 表名
     * @param key       插入列
     * @param valueList 值
     * @return
     * @author YaoS
     * @date 19/1/28 19:24
     */
    private String spliceSql(String tableName, String key, List<String> valueList) {
        StringBuffer sql = new StringBuffer();
        sql.append("insert into ").append(tableName);
        sql.append(" ( ").append(key).append(") values (");
        for (String s : valueList) {
            if (s != null) {
                sql.append("'").append(s).append("',");
            } else {
                sql.append(s).append(",");
            }
        }
        sql.deleteCharAt(sql.length() - 1);
        sql.append(")");
        return sql.toString();
    }

}
